﻿using System.Text;

namespace Kaleida.ServiceMonitor.Model.Runtime
{
    public class DefaultStatePresentation : IStatePresentation
    {
        private readonly IMonitorState state;

        public DefaultStatePresentation(IMonitorState state)
        {
            this.state = state;
        }

        public string GetNotificationWord()
        {
            if (state.FailureCount != 0)
                return ":-(";

            if (state.IsMonitoring)
                return ":-)";
            
            return "";
        }

        public string GetStateSummary()
        {
            if (state.FailureCount != 0)
                return string.Format("{0} error(s)", state.FailureCount);

            if (state.IsMonitoring)
                return "Monitoring";
            
            return "Not Monitoring";
        }

        public string GetStateDetail()
        {
            if (state.FailureCount == 0)
                return "";
        
            var description = new StringBuilder();

            description.Append(state.FailureCount);
            description.AppendFormat(" error{0}:\r\n", state.FailureCount == 1 ? "" : "s");

        	var firstError = state.FirstFailureOrDefault;
        	var latestError = state.LatestFailureOrDefault;

            if (firstError != null && latestError != null)
            {
                if (firstError != latestError)
                {
                    description.AppendFormat("    First:  {0:G} {1}\r\n", firstError.ErrorDateTime, firstError.Exception.Message);
                    description.AppendFormat("    Latest: {0:G} {1}\r\n", latestError.ErrorDateTime, latestError.Exception.Message);
                }
                else
                {
                    description.AppendFormat("    {0:G} {1}\r\n", latestError.ErrorDateTime, latestError.Exception.Message);
                }
            }

            return description.ToString();
        }
    }
}
